package com.fdq.dianping.interceptor;

import com.fdq.dianping.util.Constants;
import com.fdq.dianping.util.JwtUtil;
import com.fdq.dianping.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//刷新用户token,已登录的用户刷新，未登录的用户什么都不做
public class TokenRefreshInterceptor implements HandlerInterceptor {
    private RedisTemplate<String,Object> objectRedisTemplate;

    public TokenRefreshInterceptor(RedisTemplate<String, Object> objectRedisTemplate) {
        this.objectRedisTemplate = objectRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("aaa");
        //用jwt
        //jwt码
        String token = request.getHeader("Authorization");
        //从jwt中解析出的数据
        Map<String, Object> claim = null;
        try{
            //判断该token是否有效
            String redis_token =  objectRedisTemplate.opsForValue().get(Constants.Token_Prefix + token).toString();
            if(redis_token.isEmpty()){
                //直接放行，不给threadLocal赋值
                return true;
            }
            claim = JwtUtil.parseToken(token);
            //使用threadLocal保存用户信息
            ThreadLocalUtil.set(claim);
            //刷新有效时间
            objectRedisTemplate.expire(Constants.Token_Prefix+token,Constants.User_Token_TTL, TimeUnit.MINUTES);
            return true;
        }catch (Exception e){
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
